import StatusNav from '@/components/school/statusNav';
import PageBody from '@/components/school/pageBody';
import {mapGetters} from "vuex";
import {toLogin} from '@/libs/login.js';
import diyJson from '@/config/diy.js';
import * as AccountInfo from '@/api/member/memberAccountCard.js'
import * as memberAccountRecordApi from '@/api/member/memberAccountRecord.js'
import * as WeixinApi from '@/api/weixin/weixin.js'
import UvUpload from '@/components/school/uv-upload';
import Dict from '@/components/school/dict';
import {BASE_CONFIG} from "@/config/app";
const app = getApp();

// #ifdef H5
let wx = require('jweixin-module');
// #endif

export const mixins = {
  computed: mapGetters(['isLogin', 'userInfo']),
  components: {
    StatusNav,
    PageBody,
    UvUpload,
    Dict
  },
  data() {
    return {
      themConfig: diyJson.commonStyle,
      formData: {},
      rules: {
      },
      pageBody: {
        marginBottom: 55,
      },
      activeIndex: 0,
      activeSubIndex: 0,
      tabSubList: [
        {
          name: '全部',
          value: ''
        }, {
          name: '审核中',
          value: '0'
        }
        , {
          name: '银行处理中',
          value: '1'
        }
        , {
          name: '待收款用户确认',
          value: '3'
        }
        , {
          name: '已完成',
          value: '2'
        }
        ,{
          name: '失败',
          value: '-1'
        }
      ],

      loading: {
        status: 'nomore',
        loadingText: '加载中',
        loadmoreText: '点击加载更多',
      },

      accountInfoCard: undefined,
      searchParams: {
        type: '1' //  收支类型:1=收入，2=支出
      },

      dataList: [], // 收支明细
      dataPage: {
        current: 1,
        pages: 0,
      },
      isReachBottom: false,
      accountInfo: {
        todayProfit: 0.00,
        "total": 0.00,
        "balance": 0.00,
        "withdrawal": 0.00
      },

      statusNavProperties: { // 筛选条件
        title: "佣金提现",
        setStyle: {
          bgColor: 'white',
          enableBack: true,
          titleStyle: {}
        }
      },

    };
  },

  watch: {},

  mounted() {
    this.computeAmountHeight();
  },

  methods: {

    // 图片放大
    imgOpenLager(e) {
      uni.previewImage({
        urls: [e], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
        current: '', // 当前显示图片的http链接，默认是第一个
        success: function (res) {
        },
        fail: function (res) {
        },
        complete: function (res) {
        },
      })
    },

    async computeAmountHeight() {
      const query = uni.createSelectorQuery().in(this);
      let that = this;
      query.select('.heightWrapper')
      .boundingClientRect((dome) => {
        // console.log("height", dome.height)
        // that.pageBody['paddingTop'] = dome.height;
      })
      .exec();
    },

    // 点击提现
    clickSettle() {
      if (this.accountInfoCard === undefined || this.accountInfoCard === null) {
        uni.navigateTo({
          url: '/pages/users/user_set_settle_info/index'
        })
        return;
      }
      this.$refs.popup.open();
    },

    // 收支记录
    getList(params) {
      this.dataList = [];
      memberAccountRecordApi.getList(params).then(res => {
        this.dataList = res.data.records;
        this.dataPage.current = res.data.current;
        this.dataPage.pages = res.data.pages;
      })
    },

    // 进出帐tab
    tabChange(e) {
      console.log("eee", e);
      this.$nextTick(() => {
        this.loading.status = 'nomore';
        this.activeSubIndex = e.index;
        this.searchParams.state = e.value;
        this.getList({...this.searchParams})
      })
    },

    // 获取账户金额
    getAccountInfo() {
      memberAccountRecordApi.computeSettleAmount().then((res) => {
        this.accountInfo['balance'] = res.data.amount;
        let from  = {...this.formData};
        from['amount'] = res.data.amount;
        from['actualAmount'] = res.data.actualAmount;
        from['fee'] = res.data.fee;
        from['tip'] = res.data.tip;
        from['allow'] = res.data.allow;
        from['withdrawalConfig'] = res.data.withdrawalConfig;
        this.formData = from;
      })
    },

    scrolltolower() {
      this.isReachBottom = true;
      this.loading.status = 'nomore';
      if (this.dataPage.current < this.dataPage.pages) {
        this.loading.status = 'loadmore';
      }
    },

    goBack(url) {
      // #ifdef H5
      return history.back();
      // #endif
      // #ifndef H5
      return uni.navigateBack({
        delta: 1,
      })
      // #endif
    },

    loadmore() {
      if (this.dataPage.current < this.dataPage.pages) {
        this.loading.status = 'loading';
        memberAccountRecordApi.getList(
            {...this.searchParams, current: this.dataPage.current + 1}).then(
            res => {

              res.data.records.forEach(item => {
                this.dataList.push(item)
              })
              this.dataPage.current = res.data.current;
              this.dataPage.pages = res.data.pages;
              this.loading.status = 'loadmore';
            })
      }
    },

    // 获取用户卡信息
    getCardInfo() {
      AccountInfo.getByUserId(this.userInfo.id).then(res => {
        this.formData['accountInfo'] = res.data.bankName + '('
            + res.data.bankCardNo + ')';
        this.accountInfoCard = res.data;
      })
    },

    submit() {
      // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
      this.$refs.form.validate().then(res => {
        memberAccountRecordApi.settle({
          amount: this.formData.amount,
          actualAmount: this.formData.actualAmount,
          concatPhone: this.formData.concatPhone,
          memberRemark: this.formData.memberRemark
        }).then(res => {
          uni.showToast({
            title: "申请已提交，48小时内审核到账",
            icon: 'success'
          });
          this.$refs.popup.close();
          this.getAccountInfo();
        })
      }).catch(errors => {
        console.log("errors", errors, this.formData)
      })
    },


    // 确认收款
    userConfirm(e){
      let packageInfo = e.packageInfo;
      let configParams = {
        // currentFullPageUrl: location.href.split("#")[0],
        currentFullPageUrl: "https://campus.noseenogo.online/pages/users/user_cash/index",
        appId: BASE_CONFIG.appId,
        jsApiList: [
          "requestMerchantTransfer"
        ],
        debug: false
      }
      uni.showLoading({
        title: '处理中',
      });

      WeixinApi.getWxSdkConfig(configParams).then(r=>{
        let config ={...r.data}
        delete config['currentFullPageUrl'];
        console.log("config",config);
        uni.hideLoading();

        // #ifdef H5
        wx.config(config);
        uni.showLoading({
          title: '处理中',
        });
        // 拉起收款确认弹框
        wx.ready(function () {
          wx.checkJsApi({
            jsApiList: ['requestMerchantTransfer'],
            success: function (res) {
              uni.hideLoading();
              if (res.checkResult['requestMerchantTransfer']) {
                WeixinJSBridge.invoke('requestMerchantTransfer', {
                      mchId: BASE_CONFIG.mchId,
                      appId: r.data.appId,
                      package: packageInfo,
                    },
                    function (res) {
                      if (res.err_msg === 'requestMerchantTransfer:ok') {
                         // res.err_msg将在页面展示成功后返回应用时返回success，并不代表付款成功
                      }
                    }
                );
              } else {
                console.log("",res)
              }
            }
          });
        });
        // #endif


      })
    },

    getApp() {
      return app;
    },

  },

  onPullDownRefresh() {
    this.getAccountInfo();
    this.getList({...this.searchParams});
    uni.stopPullDownRefresh();
  },
  onLoad: function (options) {
    if (!this.isLogin) {
      toLogin();
    }
  },
  onShow() {
    this.getAccountInfo();
    this.getCardInfo();
    this.formData['concatPhone'] = this.userInfo.phone;
    this.getList({...this.searchParams});
  },
  onReady() {
  },
  onReachBottom() {
    this.scrolltolower();
  }
}
